package com.woniuxy.opencv.service.impl;

import com.woniuxy.opencv.client.VehicleClient;
import com.woniuxy.opencv.pojo.ParkingOrder;
import com.woniuxy.opencv.pojo.ParkingRecord;
import com.woniuxy.opencv.pojo.Vehicle;
import com.woniuxy.opencv.service.ParkingOrderService;
import com.woniuxy.opencv.service.ParkingService;
import com.woniuxy.opencv.service.ParkingRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class ParkingServiceImpl implements ParkingService {

    @Autowired
    private ParkingRecordService parkingRecordService;
    
    @Autowired
    private VehicleClient vehicleClient;
    
    @Autowired
    private ParkingOrderService parkingOrderService;

    @Autowired
    private LockService lockService;

    // 默认停车场ID，可以通过配置文件配置
    private static final Integer DEFAULT_PARKING_ID = 1;
    
    // 临时车收费标准（元/小时）
    private static final double TEMP_VEHICLE_RATE = 5.0;


    @Override
    @Transactional
    public ParkingRecord handleEntry(String licensePlate) {
        // 查询车辆信息
        ResponseEntity<Vehicle> response = vehicleClient.checkVehicle(licensePlate);
        Vehicle vehicle = response.getBody();
        
        // 判断是否是业主的月租车（status=1表示正常状态）
        Integer vehicleType = null; // 修改：初始值设为 null
        
        if (vehicle != null) {
            boolean isValidStatus = vehicle.getStatus() != null && vehicle.getStatus() == 1;
            boolean hasOwner = vehicle.getOwnerId() != null;
            
            if (isValidStatus && hasOwner) {
                vehicleType = 1; // 月租车
            } else {
                vehicleType = 0; // 临时车
            }
        } else {
            vehicleType = 0; // 未登记车辆作为临时车
        }
        if (vehicleType == null) {
            throw new RuntimeException("无法确定车辆类型");
        }
        // 记录入场
        return parkingRecordService.recordVehicleEntry(licensePlate, DEFAULT_PARKING_ID, vehicleType);
    }

    @Override
    @Transactional
    public ParkingRecord handleExit(String licensePlate) {
        log.info("处理车辆出场 - 车牌号: {}", licensePlate);
        
        // 记录出场时间
        ParkingRecord record = parkingRecordService.recordVehicleExit(licensePlate, DEFAULT_PARKING_ID);
        
        // 生成订单ID
        Long orderId = generateOrderId(record);
        record.setOrderId(orderId);  // 修改：使用String类型的订单ID
        
        // 如果是月租车，创建金额为0的订单
        if (record.getVehicleType() == 1) {
            parkingOrderService.createOrder(record, 0.0);
            parkingRecordService.updateById(record);
            // 新增：月租车出场后自动开锁
            if (record.getParkingId() != null) {
                lockService.handleLockOperation(record.getParkingId());
                log.info("月租车出场后已调用开锁服务，lockId: {}", record.getParkingId());
            } else {
                log.warn("月租车出场但parkingId为空，无法开锁，plateNumber: {}", licensePlate);
            }
            return record;
        }
        
        // 计算停车费用
        double fee = calculateParkingFee(record);
        log.info("临时车出场，计算费用 - 车牌号: {}, 费用: {}", licensePlate, fee);
        
        // 创建订单
        ParkingOrder order = parkingOrderService.createOrder(record, fee);
        log.info("创建停车订单成功 - 订单ID: {}", order.getId());
        
        // 更新记录
        parkingRecordService.updateById(record);
        
        return record;
    }

    @Override
    public ParkingRecord queryCurrentRecord(String licensePlate) {
        return parkingRecordService.getVehicleCurrentParkingStatus(licensePlate);
    }

    @Override
    public double calculateParkingFee(ParkingRecord record) {
        if (record == null || record.getStartTime() == null) {
            return 0.0;
        }
        // 如果是月租车，不收费
        if (record.getVehicleType() == 1) {
            return 0.0;
        }
        // 如果还没有结束时间，使用当前时间计算
        Date endTime = record.getEndTime() != null ? record.getEndTime() : new Date();
        // 计算停车时长
        long parkingTimeMillis = endTime.getTime() - record.getStartTime().getTime();
        double parkingHours = Math.ceil(parkingTimeMillis / (double) TimeUnit.HOURS.toMillis(1));
        double fee = parkingHours * TEMP_VEHICLE_RATE;
        return fee;
    }

    /**
     * 生成订单ID
     * 格式：年月日时分秒+3位车位ID（15位数字）
     */
    private Long generateOrderId(ParkingRecord record) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
        String timeStr = sdf.format(new Date());
        // 使用车位ID作为后缀，补齐3位
        String parkingIdStr = String.format("%03d", record.getParkingId());
        String orderId = timeStr + parkingIdStr;
        log.info("生成订单号 - 车牌号: {}, 订单号: {}", record.getPlateNumber(), orderId);
        return Long.parseLong(orderId);
    }
} 